import Vue from 'vue'
import Vuex from 'vuex'
import _ from '../libs/js/lodash.js';
import { getUserInfo, logout } from '../libs/js/api.js';
Vue.use(Vuex)

let lifeData = {}

// 尝试获取本地是否存在lifeData变量，第一次启动时不存在
try {
  lifeData = uni.getStorageSync('lifeData')
} catch(e) {
  
}

// 标记需要永久存储的变量，在每次启动时取出，在state中的变量名
let saveStateKeys = ['vuex_user']

// 保存变量到本地存储
const saveLifeData = function(key, value) {
  // 判断变量是否在存储数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmpLifeData = uni.getStorageSync('lifeData')
    // 第一次启动时不存在，则放一个空对象
    tmpLifeData = tmpLifeData ? tmpLifeData : {},
    tmpLifeData[key] = value
    // 将变量再次放回本地存储中
    uni.setStorageSync('lifeData', tmpLifeData)
  }
}

const store = new Vuex.Store({
  state: {
    // 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
    // 加上vuex_前缀，是防止变量名冲突，也让人一目了然
    vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {name: '本子娘'},
    userInfo: {},
    userId: uni.getStorageSync('userId'),
    token: uni.getStorageSync('appIdToken'),
    tokenExpired: uni.getStorageSync('apptokenExpired'),
    cdn: uni.getStorageSync('appCdn'),
    commonTags: uni.getStorageSync('commonTags') ||  {},
    offenTags: uni.getStorageSync('offenTags') || [],
    // 如果vuex_version无需保存到本地永久存储，无需lifeData.vuex_version方式
    // app版本
    vuex_version: "1.0.0",
    doLogin: false,
    // 是否使用自定义导航栏
    vuex_custom_nav_bar: true,
    // 状态栏高度
    vuex_status_bar_height: 0,
    // 自定义导航栏的高度
    vuex_custom_bar_height: 0
  },
  getters: {
  	userInfo: state => state.userInfo,
    userId: state => state.userId,
  	token: state => state.token,
    commonTags: state => state.commonTags,
    offenTags: state => state.offenTags,
  	cdn: state => state.cdn,
    doLogin: state => state.doLogin,
  	hasLogin(state) { return !!state.token }
  },
  mutations: {
    $tStore(state, payload) {
      // 判断是否多层调用，state中为对象存在的情况，例如user.info.score = 1
      let nameArr = payload.name.split('.')
      let saveKey = ''
      let len = nameArr.length
      if (len >= 2) {
        let obj = state[nameArr[0]]
        for (let i= 1; i < len - 1; i++) {
          obj = obj[nameArr[i]]
        }
        obj[nameArr[len - 1]] = payload.value
        saveKey = nameArr[0]
      } else {
        // 单层级变量
        state[payload.name] = payload.value
        saveKey = payload.name
      }
      
      // 保存变量到本地中
      saveLifeData(saveKey, state[saveKey])
    },
    setStateAttr(state, param){
    	if(param instanceof Array){
    		for(let item of param){
    			state[item.key] = item.val;
    		}
    	}else{
    		state[param.key] = param.val;
    	}
    },
    pushTags(state, data) {
      if(state.commonTags[data]){
        state.commonTags[data] += 1;
      }else{
        state.commonTags[data] = 1;
      }
      const offenTags = _.sortBy(_.uniq(Object.keys(state.commonTags)),
      function(o){
        return -state.commonTags[o]
      });
      state.offenTags = offenTags;
      console.log(offenTags, state.commonTags)
      uni.setStorageSync('offenTags', state.offenTags);
      uni.setStorageSync('commonTags', state.commonTags);
    },
    setCdn(state, data) {
    	state.cdn = data;
    	uni.setStorageSync('appCdn', data);
    },
    setDologin(state){
      state.doLogin = true; 
    },
    setToken(state, data){
    	const {token} = data;
    	state.token = token;
    	uni.setStorageSync('appIdToken', token);
    },
    //退出登录
    logout(state){
    	state.token = '';
    	uni.removeStorageSync('appIdToken');
    	setTimeout(()=>{
    			state.userInfo = {};
    	}, 1100)
    },
    setCdn(state, data) {
    	state.cdn = data;
    	uni.setStorageSync('appCdn', data);
    },
  },
  actions: {
    async getUserInfo({state, commit}){
    	const res = await getUserInfo();
    	if(res.code === 0) {
    		const userInfo = res.data;
        if(userInfo){
          if(res.data.id){
          	commit('setStateAttr', {
          		key: 'userInfo',
          		val: res.data
          	});
            uni.setStorageSync('userId', res.data.id);
          	commit('setCdn', res.data.cdn)
          }else{
          	commit('logout', state)
          }
        }
    	}
    },
    async logout({state, commit}){
    	await logout();
    	commit('logout', state);
    	uni.navigateTo({
    		url: '/pages/login/login'
    	})
    },
  }
})

export default store